package com.gettagger.tagger.activities;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.gettagger.tagger.R;
import com.gettagger.tagger.dao.TaggerDataRetriever;
import com.gettagger.tagger.models.AccountObject;
import com.gettagger.tagger.models.GuardianObject;
import com.gettagger.tagger.models.TaggerConstants;
import com.google.gson.Gson;

public class ActLogin extends Activity {

	private SharedPreferences sharedPref = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		sharedPref = getSharedPreferences(TaggerConstants.PREFERENCE_NAME, Context.MODE_PRIVATE);

		if (sharedPref.getBoolean(TaggerConstants.PREFERENCE_SESSION, false)) {
			Intent intent = new Intent(ActLogin.this, ActMain.class);
			startActivity(intent);
		}

		setContentView(R.layout.act_login);

		final EditText etUsername = (EditText) findViewById(R.id.login_edittext_username);
		final EditText etPassword = (EditText) findViewById(R.id.login_edittext_password);

		TextView txtContinue = (TextView) findViewById(R.id.login_continue);
		txtContinue.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String uName = etUsername.getText().toString();
				String pas = md5(etPassword.getText().toString());

				String[] param = { uName, pas };
				new DisplayDataTask().execute(param);

			}
		});

	}

	public String md5(String s) {
		try {
			// Create MD5 Hash
			MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
			digest.update(s.getBytes());
			byte messageDigest[] = digest.digest();

			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			for (int i = 0; i < messageDigest.length; i++)
				hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
			return hexString.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			showErrorMessage("Error in security conversion.");
		}
		return "";
	}

	private class DisplayDataTask extends AsyncTask<String, Void, Void> {
		ArrayList<GuardianObject> gObj = null;
		private final ProgressDialog dialog = new ProgressDialog(ActLogin.this);
		private String errorMsg = "";

		protected void onPreExecute() {
			if (!this.dialog.isShowing()) {
				this.dialog.setMessage("Retrieving Data...");
				this.dialog.show();
			}
		}

		protected void onPostExecute(final Void unused) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}

			if (errorMsg.length() > 0) {
				showErrorMessage(errorMsg);
			} else {
				if (gObj != null) {
					if (gObj.size() > 0) {
						// Save User info to shared preference
						saveUserInfo(gObj.get(0));
						// PROMPT Successful Login
						Toast.makeText(ActLogin.this, "Login Successful", Toast.LENGTH_SHORT).show();
						// Kill Activity
						finish();
						// Save session to shared preference
						setSignedIn(true);
						// Transition to Main Activity
						Intent intent = new Intent(ActLogin.this, ActMain.class);
						startActivity(intent);

					} else {
						setSignedIn(false);
						Toast.makeText(ActLogin.this, "Login Failed", Toast.LENGTH_SHORT).show();
					}
				} else {
					setSignedIn(false);
					Toast.makeText(ActLogin.this, "Login Failed", Toast.LENGTH_SHORT).show();
				}
			}

		}

		@Override
		protected Void doInBackground(String... param) {
			TaggerDataRetriever dr = new TaggerDataRetriever();

			try {
				gObj = dr.verifyAccount(param[0], param[1]);
			} catch (Exception e) {
				e.printStackTrace();
				errorMsg = e.getMessage();
			}

			return null;
		}
	}

	private void showErrorMessage(String errorMessage) {
		AlertDialog.Builder builder = new AlertDialog.Builder(ActLogin.this);
		builder.setIcon(0);
		builder.setTitle("Error");
		builder.setMessage(errorMessage);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int id) {
				dialog.cancel();
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	private void setSignedIn(boolean val) {
		Editor editor = sharedPref.edit();
		editor.putBoolean(TaggerConstants.PREFERENCE_SESSION, val);
		editor.commit();
	}

	private void saveUserInfo(GuardianObject data) {
		if (data != null) {

			String jsonData = "";
			Gson gson = new Gson();
			jsonData = gson.toJson(data);

			Editor editor = sharedPref.edit();
			editor.putString(TaggerConstants.PREFERENCE_USER_INFO, jsonData);
			editor.commit();
		}
	}

}
